﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using Eassets.Service.Global;
using Eassets.Layered.Domain.Global;
using Eassets.Service.Asset;
using Eassets.Layered.Domain.Asset;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;

namespace Eassets.UI.Asset
{
    public partial class AssetsRevaluationForm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (dropDownListMainCategory.DataSource == null)
            {
                GetAllMainCategory();
            }

            GetOrganizationLevelList();
        }

        private void GetOrganizationLevelList()
        {
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists =
                organizationLevelListService.GetAllOrganizationLevelList().Where(x => x.OrganizationLevelMode == "B").
                    ToList();
            dropDownListOrganizationLevelList.DataSource = organizationLevelLists;
            dropDownListOrganizationLevelList.DataValueField = "OrganizationLevelListId";
            dropDownListOrganizationLevelList.DataTextField = "Code";
            dropDownListOrganizationLevelList.DataBind();
        }

        protected void dropDownListOrganizationLevelList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListOrganizationLevelList.SelectedValue != "0")
            {
                DataBindToTransactionNumber();
                dropDownListTransactionNo.Enabled = true;
            }

        }

        private void DataBindToTransactionNumber()
        {
            dropDownListTransactionNo.Items.Clear();
            TransactionService transactionService = new TransactionService();
            List<Transaction> transactionsList = new List<Transaction>();
            transactionsList =
                transactionService.GetTransactionNoByOrgLevelListId(
                    Convert.ToInt64(dropDownListOrganizationLevelList.SelectedItem.Value)).ToList();
                
            dropDownListTransactionNo.DataSource = transactionsList;
            dropDownListTransactionNo.DataTextField = "TransactionNo";
            dropDownListTransactionNo.DataValueField = "TransactionId";
            dropDownListTransactionNo.DataBind();
        }

        private void GetAllMainCategory()
        {
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListMainCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                dropDownListMainCategory.DataValueField = "CategoryId";
                dropDownListMainCategory.DataTextField = "Description";
                dropDownListMainCategory.DataBind();

            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListMainCategory.SelectedValue != "0")
            {
                GetAllSubCategory();
            }

        }

        private void GetAllSubCategory()
        {
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListSubCategory.DataSource =
                    categoryService.GetAllAssetCategory().Where(
                        x => x.ParentId == Convert.ToInt32(dropDownListMainCategory.SelectedValue)).ToList();

                dropDownListSubCategory.DataValueField = "CategoryId";
                dropDownListSubCategory.DataTextField = "Description";
                dropDownListSubCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dropDownListSubCategory.SelectedValue != "0")
            {
                GetAssets();
            }

        }

        private void GetAssets()
        {
            AssetService assetService = new AssetService();
            Assets assets = new Assets();
            try
            {
                dropDownListAsset.DataSource =
                    assetService.GetAllAsset().Where(
                        x => x.AssetCategoryId == Convert.ToInt32(dropDownListSubCategory.SelectedValue)).ToList();

                dropDownListAsset.DataValueField = "AssetId";
                dropDownListAsset.DataTextField = "Description";
                dropDownListAsset.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void dropDownListAsset_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataBindToGridView();
        }

        protected void DataBindToGridView()
        {
            List<AssetItemDetails> assetItemDetails = new List<AssetItemDetails>();
            assetItemDetails = GetFixedAssetItemDetailsByAssetId(Convert.ToInt64(dropDownListAsset.SelectedValue)).ToList();
            //assetItemDetails =
            //    (from AssetItemDetail in assetItemDetails
            //     where AssetItemDetail.AssetStatus != "DIS"
            //     select AssetItemDetail).ToList();

            gridViewAssetDetails.DataSource = assetItemDetails;
            gridViewAssetDetails.DataBind();
        }

        protected Collection<AssetItemDetails> GetFixedAssetItemDetailsByAssetId(long assetId)
        {
            Collection<AssetItemDetails> assetItemDetails = new Collection<AssetItemDetails>();
            AssetRevaluationDetailsService assetRevaluationDetailsService = new AssetRevaluationDetailsService();
            assetItemDetails = assetRevaluationDetailsService.GetFixedAssetItemDetailsByAssetId(assetId); ;
            return assetItemDetails;
        }

        protected void textBoxChangedValue_OnTextChanged(object sender, EventArgs e)
        {
            decimal changedValue = Convert.ToDecimal(textBoxChangedValue.Text);
            textBoxChangedValue.Text = changedValue.ToString("###,###.00000");
            textBoxRevalueDate.Text = DateTime.Now.ToString("d");
            //DateTime now = DateTime.Now;
            //Console.WriteLine(now.ToString("d"));
            //String.Format(DateTime.Today.ToString(),"dd/mm/yyyy");


        }

        protected void gridViewAssetDetails_SelectedIndexChange(object sender, EventArgs e)
        {
            GridViewRow row = gridViewAssetDetails.SelectedRow;
            if (row != null)
            {
                ViewState["SerialCode"] = row.Cells[3].Text.Trim();
                ViewState["CurrentBookValue"] = row.Cells[5].Text.Trim();
                textBoxNewLifeTime.Text = row.Cells[6].Text.Trim();
                ViewState["NewLifeTime"] = row.Cells[6].Text.Trim();
                textBoxChangedValue.Text = string.Empty;
                textBoxRevalueDate.Text = string.Empty;
            }
        }

        protected void buttonSave_OnClick(object sender, EventArgs e)
        {
            try
            {
                TransactionService transactionService = new TransactionService();
                AssetRevaluationDetailsService assetRevaluationDetailsService = new AssetRevaluationDetailsService();
                Transaction transaction = new Transaction();
                transaction.TransactionTypeCode = Convert.ToString("ASREV");
                transaction.TransactionDocumentCode = Convert.ToString("REV");
                transaction.CompanyId = 0;
                transaction.OrganizationLevelListId = Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue);
                int serial = Getserial();
                dropDownListTransactionNo.SelectedItem.Text = Convert.ToString(CreateNewTransactionCode((serial + 1)));
                dropDownListTransactionNo.Enabled = false;
                //transaction.TransactionNo = "GAM/PRN/20120830/000001";
                transaction.TransactionNo = Convert.ToString(CreateNewTransactionCode((serial + 1)));
                transaction.TransactionUserId = 1;
                transaction.TransactionStatus = "A";
                //transaction.TransactionDate = DateTime.Now;
                transactionService.AddTransaction(transaction);

                long transactionId = transactionService.GetMaxTransactionNumber();


                //for (int i = 0; i < assetProcurementDetails.TransactionLine; i++)
                //{
                AssetRevaluationDetails assetRevaluationDetails = new AssetRevaluationDetails();

                assetRevaluationDetails.TransactionId = transactionId;
                assetRevaluationDetails.CompanyId = 1;
                assetRevaluationDetails.AssetId = Convert.ToInt64(dropDownListAsset.SelectedValue);
                ViewState["AssetId"] = assetRevaluationDetails.AssetId;
                assetRevaluationDetails.ItemSerialCode = ViewState["SerialCode"].ToString();
                ViewState["AssetSerialCode"] = assetRevaluationDetails.ItemSerialCode;
                assetRevaluationDetails.RevalueDate = Convert.ToDateTime(textBoxRevalueDate.Text);
                assetRevaluationDetails.RevalueValue = Convert.ToDecimal(textBoxChangedValue.Text);
                assetRevaluationDetails.NewLifeTime = Convert.ToInt16(textBoxNewLifeTime.Text);
                assetRevaluationDetails.OriginatedBy = "1";
                assetRevaluationDetails.RevalueReason = textBoxRevalueReason.Text;
                assetRevaluationDetailsService.AddAssetRevaluationDetails(assetRevaluationDetails);

                //Get the SerialCode to be Disposal

                AssetItemDetailsService assetItemDetailsService = new AssetItemDetailsService();
                AssetItemDetails assetItemDetails = new AssetItemDetails();
                assetItemDetails.AssetId = Convert.ToInt64(dropDownListAsset.SelectedValue);
                assetItemDetails.ItemSerial = ViewState["AssetSerialCode"].ToString();
                assetItemDetails.AssetStatus = Convert.ToString("REV");
                assetItemDetailsService.UpdateAssetItemDetailsStatus(assetItemDetails);

                //Update TransactionSerial Table
                TransactionSerialService transactionSerialService = new TransactionSerialService();
                transactionSerialService.UpdateTransactionSerial("REV");

                //Update AssetItemDetails Current Book Value and 
                decimal changedvalue = Convert.ToDecimal(textBoxChangedValue.Text);
                assetItemDetails.CurrentBookValue = changedvalue;
                assetItemDetails.RemainingLifeTime = Convert.ToInt16(textBoxNewLifeTime);
                assetItemDetailsService.UpdateAssetItemDetailsWithCurrentBookValueAndRemLifeTime(assetItemDetails);

            }
            catch (Exception)
            {


            }

        }


        private int Getserial()
        {
            long transactionSerial = 0;
            TransactionSerialService transactionSerialService = new TransactionSerialService();

            transactionSerial = transactionSerialService.GetMaxTransactionSerialByWorkFlowDocumentCode("REV");
            return Convert.ToInt16(transactionSerial);
        }

        private String CreateNewTransactionCode(int maxSerial)
        {

            // int maxSerial = (Convert.ToInt16(transactionSerialDomain.Serial)+1);
            string maxSerialFormated;
            maxSerialFormated = CreateNumberFormat(Convert.ToInt16(maxSerial));
            Regex regex = new Regex("-");
            string locationCode = dropDownListOrganizationLevelList.SelectedItem.Text;
            string[] arrayParameters = regex.Split(locationCode);
            String yearMonth = DateTime.Now.ToString("yyyyMM");

            string OrganizationLevelListCode = Convert.ToString(arrayParameters[0]);

            string NewTransactionCode = (OrganizationLevelListCode + "/"
                                     + "REV" + "/"
                                     + yearMonth + "/"
                                   + maxSerialFormated);
            return NewTransactionCode;
        }

        private String CreateNumberFormat(Int16 maxSerial)
        {
            string maxSerialCode;
            if ((maxSerial / 10) == 0)
            {
                maxSerialCode = "0000" + maxSerial;
            }
            else if ((maxSerial / 100) == 0)
            {
                maxSerialCode = "000" + maxSerial;
            }
            else if ((maxSerial / 1000) == 0)
            {
                maxSerialCode = "00" + maxSerial;
            }
            else if ((maxSerial / 10000) == 0)
            {
                maxSerialCode = "0" + maxSerial;
            }
            else
            {
                maxSerialCode = maxSerial.ToString();
            }
            return maxSerialCode;
        }

        //private void DataBindToItemDetails()
        //{
        //    DataTable dataTable1 = new DataTable();
        //    dataTable1.Columns.Add("Asset");
        //    dataTable1.Columns.Add("Item Serial");
        //    dataTable1.Columns.Add("RevalueDate");
        //    dataTable1.Columns.Add("ChangedValue");
        //    dataTable1.Columns.Add("NewLifeTime");
        //    dataTable1.Columns.Add("Reason");


        //    DataRow dataRow1 = dataTable1.NewRow();

        //    dataRow1["Asset"] = "Table000001";
        //    dataRow1["Item Serial"] = "000001";
        //    dataRow1["RevalueDate"] = "12/10/2011";
        //    dataRow1["ChangedValue"] = "60000";
        //    dataRow1["NewLifeTime"] = "60";
        //    dataRow1["Reason"] = "";

        //    try
        //    {
        //        dataTable1.Rows.Add(dataRow1);
        //        gridViewAssetDetails.DataSource = dataTable1;
        //        gridViewAssetDetails.DataBind();
        //    }

        //    catch (Exception ex)
        //    {

        //    }

        // }
    }
}